package com.dong.aoptools.premain.handler;

import com.dong.aoptools.cast.cls.ClassAOPVisitor;
import com.dong.aoptools.constant.PropertiesConst;
import com.dong.aoptools.util.PathUtils;
import com.dong.aoptools.util.PropertiesUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

/**
 * @description: AOP工具处理类
 * @author: 陈瑞东
 * @create: 2021-11-29 15:31
 */
public class AOPHandler implements CommonHandler {
    @Override
    public byte[] doHandler(ClassLoader loader, String className, byte[] classfileBuffer) {
        // 获取配置的扫描包
        String pkg = PropertiesUtils.getConfigProperty(PropertiesConst.CONFIG_FIELD_PACKAG_SCAN, "com.dong");
        // 将 . 转成 /
        pkg = PathUtils.point2Slash(pkg);
        // 过滤类
        if (className.contains(pkg)) {
            return getBytes(loader, className, classfileBuffer);
        }
        return classfileBuffer;
    }

    private byte[] getBytes(ClassLoader loader, String className, byte[] classfileBuffer) {
        ClassReader cr = new ClassReader(classfileBuffer);
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        ClassAOPVisitor cav = new ClassAOPVisitor(cw);
        cr.accept(cav, ClassReader.EXPAND_FRAMES);
        return cw.toByteArray();
    }
}
